#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QDir>
#include <QSize>
#include <QProcess>
#include <QCheckBox>
#include <QMessageBox>
#include <QCloseEvent>
#include <QFile>
#include <QList>
#include <QUrl>
#include <QDebug>
#include <ffmpegwrapper.h>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(ui->pushButtonBrowseSourceVideo, SIGNAL(clicked()), this, SLOT(browseSourceVideo()));
    connect(ui->pushButtonBrowseDestinationVideo, SIGNAL(clicked()), this, SLOT(browseDestinationVideo()));
    connect(ui->pushButtonConvert, SIGNAL(clicked()), this, SLOT(convertVideo()));
    ui->progressBar->reset();
    ui->groupBox_2->hide();
    resize(width(), minimumHeight());

    ffmpegWrapper = new FFmpegWrapper(this);
    connect(ffmpegWrapper, SIGNAL(progressNotification(int)), ui->progressBar, SLOT(setValue(int)));
    connect(ffmpegWrapper, SIGNAL(finished(int)), this, SLOT(on_ffmpegwrapper_finish(int)));
    ui->pushButtonConvert->setEnabled(false);

    if (qApp->argc() == 2 && QFile::exists(qApp->argv()[1]))
    {
        QString file = qApp->argv()[1];
        ui->lineEditSourceVideo->setText(file);
        ui->lineEditDestinationVideo->setText(QString("%1.mp4").arg(file));
        ui->pushButtonConvert->setEnabled(true);
        ui->pushButtonConvert->click();
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::browseSourceVideo()
{
    QString file = QFileDialog::getOpenFileName(
            this,
            tr("Select the file you want to convert"),
            QDir::homePath(),
            tr("Video files (*.avi *.mp4 *.flv *.mkv *.mpg *.mpeg *.wmv *.mov);;All files (*.*)")
            );

    if (file.isEmpty())
        return;

    addFile(file);
}

void MainWindow::browseDestinationVideo()
{
    QString file = QFileDialog::getSaveFileName(
            this,
            tr("Save the converted file as"),
            ui->lineEditDestinationVideo->text(),
            tr("Video files (*.mp4)")
            );

    if (file.isEmpty())
        return;

    ui->lineEditDestinationVideo->setText(file);
}

void MainWindow::convertVideo()
{
    if (!QFile::exists(ui->lineEditSourceVideo->text()))
        return;

    QString inputFile = ui->lineEditSourceVideo->text();
    QString outputFile = ui->lineEditDestinationVideo->text();

    // for partial conversion set the progress bar range appropriately
    if (cutVideo())
    {
        int duration = ui->timeEditFrom->time().secsTo(ui->timeEditTo->time());
        ui->progressBar->setMaximum(10 * duration);
    }

    if (!ffmpegWrapper->convert(outputFile, fitTo320x240(), cutVideo(), ui->timeEditFrom->time(), ui->timeEditTo->time()))
    {
        QMessageBox::warning(this, tr("Error"), tr("Could not start the conversion. Exiting."));
        close();
    }

    ui->pushButtonConvert->setText(tr("Cancel"));
    disconnect(ui->pushButtonConvert, SIGNAL(clicked()));
    connect(ui->pushButtonConvert, SIGNAL(clicked()), this, SLOT(close()));
    ui->pushButtonBrowseSourceVideo->setEnabled(false);
    ui->pushButtonBrowseDestinationVideo->setEnabled(false);
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    QMainWindow::closeEvent(event);
}

void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
    if (event->mimeData()->hasUrls())
        event->acceptProposedAction();
}

void MainWindow::dropEvent(QDropEvent *event)
{
    if (event->mimeData()->hasUrls())
    {
        addFile(event->mimeData()->urls().front().toLocalFile());
        event->acceptProposedAction();
    }
}

void MainWindow::addFile(const QString &file)
{
    ffmpegWrapper->init(file);
    QSize frameSize =ffmpegWrapper->getFrameSize();

    if (!(frameSize.width() <= 320 && frameSize.height() <= 240))
    {
        ui->groupBox_2->setTitle(QString("Which video codec do you want to use? The video is %1x%2.").arg(frameSize.width()).arg(frameSize.height()));
        QSize outputFrameSize = ffmpegWrapper->fitTo(QSize(640, 360));
        ui->radioButton_3->setText(QString("Use MPEG-4. The converted file will be %1x%2.").arg(outputFrameSize.width()).arg(outputFrameSize.height()));
        outputFrameSize = ffmpegWrapper->fitTo(QSize(320, 240));
        ui->radioButton_4->setText(QString("Force h264. The converted file will be %1x%2.").arg(outputFrameSize.width()).arg(outputFrameSize.height()));
        ui->groupBox_2->show();
    }
    else
    {
        ui->groupBox_2->hide();
        resize(width(), minimumHeight());
    }

    ui->progressBar->setMaximum(10 * ffmpegWrapper->getDuration());
    ui->lineEditSourceVideo->setText(file);
    ui->lineEditDestinationVideo->setText(QString("%1.mp4").arg(file));
    ui->pushButtonConvert->setEnabled(true);
}

bool MainWindow::fitTo320x240()
{
    return ui->groupBox_2->isVisible() && ui->buttonGroup_2->checkedId() == ui->buttonGroup_2->id(ui->radioButton_4);
}

bool MainWindow::cutVideo()
{
    return ui->buttonGroup->checkedId() == ui->buttonGroup->id(ui->radioButton_2);
}

void MainWindow::on_buttonGroup_buttonClicked()
{
    bool cut = cutVideo();
    ui->timeEditFrom->setEnabled(cut);
    ui->timeEditTo->setEnabled(cut);
}

void MainWindow::on_ffmpegwrapper_finish(int code)
{
    if (code)
        QMessageBox::warning(this, tr("Error"), tr("Could convert the video file."));
    else
        QMessageBox::information(this, tr("Success"), tr("File successfully created."));
    close();
}
